//
//  SYStatusViewModel.swift
//  YANAWeibo
//
//  Created by mac on 16/5/15.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
/// cell 对应的viewmodel
class SYStatusViewModel: NSObject {
    
    var status: SYStatus?
    //转发微博内容
    var retweenContent: String?
    /// 转发数内容
    var retweetCountContent: String?
    /// 评论数
    var commentCountContent: String?
    /// 赞
    var unlikeCountContent: String?
    /// 微博来源
    var sourceContent: String?
    /// 会员等级图片
    var mBrankImage: UIImage?
    /// 认证等级类型图片
    var verifiedTypeImage: UIImage?
    
    var timeContent: String? {
        guard let creatAt = status?.created_at else {
            return nil
        }
        return NSDate.sinaDate(creatAt).sinaDateString
    }
    /// 原创微博富文本
    var originalAttributedString: NSAttributedString?
    /// 转发微博富文本
    var retweetAttributedString: NSAttributedString?
    
    init(status: SYStatus) {
        super.init()
        self.status = status
        hanleRetweetContent(status)
        
        retweetCountContent = handleCountContent(status.reposts_count, defaultTitle: "转发")
        commentCountContent = handleCountContent(status.comments_count, defaultTitle: "评论")
        unlikeCountContent = handleCountContent(status.attitudes_count, defaultTitle: "赞👍")
        // 处理来源数据
        handleSourceContent(status)
        // 处理会员登录图片
        handkeMBrankImage(status.user?.mbrank ?? 0)
        // 处理认证用户
        handleVerifiedTypeImage(status.user?.verified_type ?? 0)
        // 处理微博内容表情字符串
        originalAttributedString = handleEmoticonContentWithStaus(status.text!)
        
    }
    
    // 通过微博内容 处理里面的表情字符串转换为富文本
    private func handleEmoticonContentWithStaus(textString: String) -> NSAttributedString {
        let result = NSMutableAttributedString(string: textString)
        // 创建空的 查找结果集
        var matchResultArray = [SYMatchResult]()
        
        (textString as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4E00-\\u9FA5]+\\]") { (captureCount, captureString, captureRange, _) -> Void in
            if let emoticonStr = captureString.memory as? String {
   
                let matchResult = SYMatchResult(string: emoticonStr, range: captureRange.memory)
                
                matchResultArray.append(matchResult)
            }
        }
        
        for value in matchResultArray.reverse() {
            if let emoticon = SYEmoticonTools.shareEmoticonTools.emoticonWithEmoticonStr(value.string) {
                
                let attr = NSAttributedString.attributedWithEmoticon(emoticon, font: UIFont.systemFontOfSize(HomeFontSize))
                result.replaceCharactersInRange(value.range, withAttributedString: attr)
            }

        }
        
        return result
    }
    
    
    private func hanleRetweetContent(status: SYStatus) {
        guard let retweet = status.retweeted_status?.text else {
            return
        }
        guard let name = status.retweeted_status?.user?.screen_name else {
            return
        }
        //拼接转发微博内容
        retweenContent = "@\(name): \(retweet)"
        
        // 设置转发微博内容微博的富文本
        retweetAttributedString = handleEmoticonContentWithStaus(retweenContent!)
    }
    
    // 处理评论，转发，赞
    private func handleCountContent(count: Int, defaultTitle: String) -> String {
        if count > 0{
            if count >= 10000 {
                //处理显示格式
                let result = CGFloat(count / 1000) / 10
                let resultStr = "\(result)万"
                if resultStr.containsString(".0") {
                    return resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultStr
            } else {
                return "\(count)"
            }
        
        } else {
            return defaultTitle
        }
    }
    
    //处理来源数据
    private func handleSourceContent(status: SYStatus) {
        //判断是否存在
        guard let source = status.source else {
            return
        }
        if source.containsString("\">") {
            let startIndex = source.rangeOfString("\">")?.endIndex
            let endIndex = source.rangeOfString("</")?.startIndex
            
            if let start = startIndex, end = endIndex {
                sourceContent = source.substringWithRange(start..<end)
            }
        }
        
    }
    
    // 处理会员图片
    private func handkeMBrankImage(count: Int) {
        if count > 0 && count < 7 {
            mBrankImage = UIImage(named: "common_icon_membership_level\(count)")
        }
    }
    
    // 处理认证
    private func handleVerifiedTypeImage(verified: Int) {
        switch verified {
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
        }
    
    }
}
